package com.beer.beerfriendfinder;


import static com.beer.beerfriendfinder.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.beer.beerfriendfinder.CommonUtilities.SENDER_ID;
import static com.beer.beerfriendfinder.CommonUtilities.EXTRA_MESSAGE;

import java.util.ArrayList;
import com.google.android.gcm.GCMRegistrar;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	EditText txtChatContent;
	Button cmdEnter;
	ImageView imgShowListEmojis;
	ListView lvChatHistory;
	GridView grdEmoji;

	//Loading Control's flag variable
	boolean flagLoadGrdEmoji;
	int flagEmojiChoose;
	
	//Constant variable
	Context context;
	final String TAG = "MainActivity ";
	
	MessageAdapter messageAdapter;
	ArrayList<Message> listMessage;
	
	//Static value
	static String htmlChat;
	
	// Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;
     
    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();
     
    // Connection detector
    ConnectionDetector cd;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		context = this;
		
		setId();
		
		initFlag();
		
		initValue();
		
		initStaticVariable();
		
		setControlFunction();
		
//		registerGCM();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * set id for all views
	 */
	void setId() {
		txtChatContent = (EditText) findViewById(R.id.txtChatContent);
		cmdEnter = (Button) findViewById(R.id.cmdEnter);
		lvChatHistory = (ListView) findViewById(R.id.lvChatHistory);
		grdEmoji = (GridView) findViewById(R.id.grdEmoji);
		imgShowListEmojis = (ImageView) findViewById(R.id.imgShowListEmojis); 
	}

	/**
	 * set function for view
	 */
	void setControlFunction(){
		//set img show list emojis click:
		// - show /hide gridview icon ( list Chat) 
		imgShowListEmojis.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(grdEmoji.getVisibility() == View.GONE ){
//					lvChatHistory.setVisibility(View.GONE);
					grdEmoji.setVisibility(View.VISIBLE);
					
					//If GrdEmoji not loaded yet, load content for GrdEmoji
					if(!flagLoadGrdEmoji){
						grdEmoji.setNumColumns(10);
						AdapterEmojis adapter = new AdapterEmojis(MainActivity.this);
						grdEmoji.setAdapter(adapter);						
					}
				}else{
					grdEmoji.setVisibility(View.GONE);
				}
			}
		});
	

		
		grdEmoji.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int pos,
					long arg3) {				
				
				flagEmojiChoose = pos;
				
				int start = txtChatContent.getSelectionStart();
				Editable edt_temp = new SpannableStringBuilder(AdapterEmojis.images_hot_key[pos]);
				int length = edt_temp.length();
				edt_temp = txtChatContent.getText().insert(start,edt_temp );
				txtChatContent.setText(edt_temp);
				txtChatContent.requestFocus();
				txtChatContent.setSelection(start+length);
				
				grdEmoji.setVisibility(View.GONE);
			}
			
		});
		
		//submit chat	
		cmdEnter.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				String chatContent = txtChatContent.getText().toString();
				for( int i = 0 ; i< AdapterEmojis.images_hot_key.length; i++){
					if(chatContent.contains(AdapterEmojis.images_hot_key[i])){
						Log.e(TAG, AdapterEmojis.images_hot_key[i]);
						chatContent = chatContent.replaceAll(AdapterEmojis.images_hot_key[i], "<img src ='"
						+ AdapterEmojis.images_temp[i]
						+ "'/>");
						Log.e(TAG, chatContent);
					}
				}
				try{
					if(taskSendMessage!=null){
						taskSendMessage.cancel(true);
						taskSendMessage = null;
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				taskSendMessage = new SendMessage( chatContent, context );
				taskSendMessage.execute(null,null,null);
				
				
			}
		});
		
	}
	
	/**
	 * init all flag
	 */
	void initFlag(){
		flagLoadGrdEmoji = false;
	}

	/**
	 * Init static variable
	 * 	- String htmlChat : the string will be used to chat
	 */
	void initStaticVariable(){
		htmlChat = "";
	}
	
	/**
	 * 
	 */
	void initValue(){
		listMessage = new ArrayList<Message>();
		messageAdapter = new MessageAdapter(context, listMessage);
		lvChatHistory.setAdapter(messageAdapter);
	}
	
	/**
	 * register with google cloud messaging
	 */
	void registerGCM(){
		cd = new ConnectionDetector(getApplicationContext());
		 
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(MainActivity.this,
                    "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
         
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
 
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);
         
        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));
         
        // Get GCM registration id
        final String regId = GCMRegistrar.getRegistrationId(this);
        Log.e("regId","id: "+regId);
        
        
        // Check if regid already presents
        if (regId.equals("")) {
            // Registration is not present, register now with GCM          
            GCMRegistrar.register(this, SENDER_ID);
        } else {
            // Device is already registered on GCM
            if ( !GCMRegistrar.isRegisteredOnServer(this) ) {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {
 
                    @Override
                    protected Void doInBackground(Void... params) {
                        // Register on our server
                        // On server creates a new user
                    	Log.e("Dang Dang Ky thanh cong","Dang dang ky");
                        ServerUtilities.register(context, "abc", "abc11", regId);
                        return null;
                    }
 
                    @Override
                    protected void onPostExecute(Void result) {
                    	Log.e("Da Dang Ky thanh cong","Da Dang Ky thanh cong");
                        mRegisterTask = null;
                    }
 
                };
                mRegisterTask.execute(null, null, null);
            }
//            else{GCMRegistrar.unregister(context);}
        }
	}

	/**
     * Receiving push messages
     * */
    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String chatContent = intent.getExtras().getString(EXTRA_MESSAGE);
            if(chatContent == null || chatContent.equals(null) || chatContent.equals("")){
            	return;
            }
            Log.e(TAG,chatContent);
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());
             
            /**
             * Take appropriate action on this message
             * depending upon your app requirement
             * For now i am just displaying it on the screen
             * */
             
            // Showing received message
            
			for( int i = 0 ; i< AdapterEmojis.images_hot_key.length; i++){
				if(chatContent.contains(AdapterEmojis.images_hot_key[i])){
					Log.e(TAG, AdapterEmojis.images_hot_key[i]);
					chatContent = chatContent.replaceAll(AdapterEmojis.images_hot_key[i], "<img src ='"
					+ AdapterEmojis.images_temp[i]
					+ "'/>");
					Log.e(TAG, chatContent);
				}
			}
            listMessage.add(new Message(chatContent, false));
            messageAdapter.notifyDataSetChanged();
             
            // Releasing wake lock
            WakeLocker.release();
        }
    };
     
    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }
	
    /**
     * 
     * @author kyniema4
     *
     * Send message to server when submit button clicked
     *
     */
    class SendMessage extends AsyncTask<Void, Void, Void>{
    	
    	Context context;
    	String chatContent;
    	String regId;
    	
    	public SendMessage(String chc, Context ctx){
    		context = ctx;
    		chatContent = chc;
    	}
    	
    	@Override
		protected void onPreExecute() {
			super.onPreExecute();
			listMessage.add(new Message(chatContent, false));
			messageAdapter.notifyDataSetChanged();
			txtChatContent.setText("");
		}

		@Override
		protected Void doInBackground(Void... params) {
			String url = "http://huelive.com/vanquyet/gcm_server_php/send_message.php?";
			String reg_id = "abc";
			
			url += "regId="+reg_id +"&message="+chatContent;
			
			ServerUtilities.submitDataToServerNotDialog("", url);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
		}		
    	
    } 
    
    SendMessage taskSendMessage;
	
}
